package com.jxt.myjxtmanager.db;

import com.jxt.myjxtmanager.db.dao.Message_TaskDao;

import java.util.Collection;
import java.util.List;

import de.greenrobot.dao.query.LazyList;

/***
 * 系统消息表操作辅助类
 * 
 */
public class MessageTaskModel {

	private static MessageTaskModel instance;
	private Message_TaskDao messageDao;

	public synchronized static MessageTaskModel getInstance() {
		if (instance == null) {
			instance = new MessageTaskModel();
		}
		return instance;
	}

	private MessageTaskModel() {
		messageDao = DBHelper.getInstance().getDaoSession()
				.getMessageTaskDao();
	}

	public boolean insertOrReplace(Message_task message) {
		messageDao.insertOrReplace(message); // 30ms
		return true;
	}
	
	public boolean update(Message_task message) {
		messageDao.update(message); // 30ms
		return true;
	}

	public void insertOrReplaceAll(Collection<Message_task> message) {
		messageDao.insertOrReplaceInTx(message);
	}

	public LazyList<Message_task> lazyLoadmessage() {
		return messageDao.queryBuilder().listLazy();
	}

	/**
	 * 按时间排序
	 * @return
	 */
	public List<Message_task> loadSystemMessge() {
		return messageDao.queryBuilder().orderAsc(Message_TaskDao.Properties.Send_time).list();
	}

	public Message_task getMessageByCode(String code) {
		return messageDao.queryBuilder()
				.where(Message_TaskDao.Properties.Id.eq(code)).limit(1)
				.unique();
	}
	public List<Message_task> getMessageByStatus(int status) {
		return messageDao.queryBuilder()
				.where(Message_TaskDao.Properties.Status.eq(status)).list();
	}
	public List<Message_task> getMessageByMsgType(int msgType) {
		return messageDao.queryBuilder()
				.where(Message_TaskDao.Properties.Msg_type.eq(msgType)).list();
	}

	public void deletemessageAll() {
		messageDao.deleteAll();
	}
	public void deleteMessage(Message_task empty) {
		messageDao.delete(empty);
	}
	
	public List<Message_task> getMessageByDriverID(String Id){
		return messageDao.queryBuilder().where(Message_TaskDao.Properties.Id.eq(Id)).orderAsc(Message_TaskDao.Properties.Send_time).list();
	}
	
	/**
	 * 获取当前用户 所有已读消息
	 * @param Id
	 * @return
	 */
	public List<Message_task> getMessageByDriverIDAndUnRead(String Id){
		return messageDao.queryBuilder().where(Message_TaskDao.Properties.Id.eq(Id), Message_TaskDao.Properties.Un_read_message.eq(1)).list();
	}

	/**
	 * 所有未读消息  更新为已读
	 * @param driver_id
	 */
	public void updateMessageReadStatus(String driver_id){
		List<Message_task> messages = getMessageByDriverIDAndUnRead(driver_id);
		for (Message_task message_System : messages) {
			message_System.setUn_read_message(0);
			insertOrReplace(message_System);
		}
	}
	
}
